package com.pek.util;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pek.annontation.Permit.Permit;
import com.pek.annontation.Permit.UserPermit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

public class BaseController<T> {
    private IService<T> serviceImpl;

    public BaseController(IService<T> serviceImpl) {
        this.serviceImpl = serviceImpl;
    }

    public RestResult<Object> list(Integer size,
                                   Integer pageSize,
                                   Integer pageNo,
                                   QueryWrapper<T> wrapper) {
        return list(size, pageSize, pageNo, wrapper.lambda());
    }


    /**
     * 添加
     *
     * @param size
     * @param pageSize
     * @param pageNo
     * @param wrapper
     * @return
     */
    public RestResult<Object> list(Integer size,
                                   Integer pageSize,
                                   Integer pageNo,
                                   LambdaQueryWrapper<T> wrapper) {
        Object result;
        //如果是未传入分页
        if (pageSize == 0 || pageNo == 0) {
            wrapper.last(size != 0, String.format(" limit %s", size));
            result = serviceImpl.list(wrapper);
        }
        //如果传入了分页
        else {
            Page<T> page = new Page<>(pageNo, pageSize);
            result = serviceImpl.page(page, wrapper);
        }
        return RestResult.success(result);
    }

    /**
     * 根据id获取
     */
    public RestResult<T> query(@RequestParam String id) {
        var entity = serviceImpl.getById(id);
        if (entity == null)
            return RestResult.error("实体不存在");
        return RestResult.success(entity);
    }

    @Permit(value = {UserPermit.INSERT, UserPermit.UPDATE}, time = 500)
    public RestResult<T> save(@RequestBody T entity) {
        serviceImpl.saveOrUpdate(entity);
        return RestResult.success(entity);
    }

    @Permit({UserPermit.UPDATE})
    public RestResult<T> edit(@RequestBody T entity) {
        serviceImpl.updateById(entity);
        return RestResult.success(entity);
    }

    @Permit({UserPermit.DELETE})
    public RestResult<T> delete(@RequestParam String id) {
        serviceImpl.removeById(id);
        return RestResult.success("删除成功");
    }
}
